package com.cyzy.utils;

import com.alibaba.fastjson2.JSONObject;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

/**
 * 创建电子合同
 */
@Component
public class ElectronicContractsUtil {
    public String createContract(){
        String sourcesPath="C:\\Users\\yangjingshi\\Desktop\\四阶项目\\电子合同模板\\合同模板.pdf";
        String targetPath="C:\\Users\\yangjingshi\\Desktop\\四阶项目\\合同\\";
        //甲方
        String companyNameA="原神启动开发公司";
        String juridicalPersonA="波妞";
        String addressA="大榕树创意园";
        String phoneA="11122223333";
        //乙方
        String companyNameA1="1";
        String juridicalPersonA1="1";
        String addressA1="1";
        String phoneA1="1";
        targetPath=targetPath+companyNameA1+"_"+juridicalPersonA1+"_"+phoneA1+".pdf";
        System.out.println(targetPath);
        //金额
        String money="3000";
        String moneyChinese="三千";
        //日期
        String sday="1";
        String noday="15";
        String dateLine="3个月";
        //甲方签名
        String admin="波妞";
        String year1="2025";
        String month1="05";
        String day1="19";
        String img1="C:\\Users\\yangjingshi\\Desktop\\四阶项目\\公章\\1.png";
        //乙方签名
        String user1="1";
        String year="2025";
        String month="05";
        String day="19";
        String img="C:\\Users\\yangjingshi\\Desktop\\四阶项目\\公章\\2.png";

        //设置参数
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("companyNameA",companyNameA);
        jsonObject.put("juridicalPersonA",juridicalPersonA);
        jsonObject.put("addressA",addressA);
        jsonObject.put("phoneA",phoneA);
        jsonObject.put("companyNameA1",companyNameA1);
        jsonObject.put("juridicalPersonA1",juridicalPersonA1);
        jsonObject.put("addressA1",addressA1);
        jsonObject.put("phoneA1",phoneA1);
        jsonObject.put("money",money);
        jsonObject.put("moneyChinese",moneyChinese);
        jsonObject.put("sday",sday);
        jsonObject.put("noday",noday);
        jsonObject.put("dateLine",dateLine);
        jsonObject.put("admin",admin);
        jsonObject.put("year1",year1);
        jsonObject.put("month1",month1);
        jsonObject.put("day1",day1);
        jsonObject.put("img1",img1);
        jsonObject.put("user1",user1);
        jsonObject.put("year",year);
        jsonObject.put("month",month);
        jsonObject.put("day",day);
        jsonObject.put("img",img);


        // 填充创建pdf
        PdfReader reader=null;
        PdfStamper stamp=null;
        ByteArrayOutputStream baos=null;
        try {
            reader=new PdfReader(sourcesPath);
            File deskFile = new File(targetPath);
            stamp=new PdfStamper(reader,new FileOutputStream(deskFile));
            //取出报表模板中的所有字段
            AcroFields form = stamp.getAcroFields();
            System.err.println(form.getFields().keySet());

            //设置宋体
            BaseFont song = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            if (jsonObject!=null){
                for (Map.Entry<String,Object> entry: jsonObject.entrySet()){
                    String key = entry.getKey();
                    String value = entry.getValue().toString();
                    //保存选项
                    if (key.startsWith("select")) {
                        form.setField(key, value, true);
                        //保存文字
                    }else {
                        form.setFieldProperty(key, "textfont", song, null);
                        form.setField(key, value);
                    }


                }
            }
            //插入签名
            System.out.println(img);

            insertImage(form,stamp,"img",img);
            //插入公章
            insertImage(form,stamp,"img1",img1);
            //保存修改
            stamp.setFormFlattening(true);
            return targetPath;

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }finally {
            if (stamp != null) {
                try{
                    stamp.close();
                }catch (Exception e){
                    e.printStackTrace();
                }

            }
            if (reader != null) {
                try{
                    reader.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            if (baos != null) {
                try{
                    baos.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    public  static boolean insertImage(AcroFields form, PdfStamper stamper, String filedName, String url) {
        try {
            int pageNo = form.getFieldPositions(filedName).get(0).page;
            Rectangle signRect = form.getFieldPositions(filedName).get(0).position;
            float x = signRect.getLeft();
            float y = signRect.getBottom();

            Image image = Image.getInstance(url);
            // 获取操作的页面
            PdfContentByte under = stamper.getOverContent(pageNo);
            // 根据域的大小缩放图片
            image.scaleToFit(signRect.getWidth(), signRect.getHeight());
            // 添加图片
            image.setAbsolutePosition(x, y);
            under.addImage(image);
        }catch (Exception e){
            return false;
        }
        return true;

    }

}
